package com.ruoyi.project.system.notice.service;

import com.ruoyi.common.support.Convert;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.security.ShiroUtils;
import com.ruoyi.framework.session.SessionService;
import com.ruoyi.project.system.notice.domain.Notice;
import com.ruoyi.project.system.notice.mapper.NoticeMapper;
import com.ruoyi.project.system.noticeRecord.domain.NoticeRecord;
import com.ruoyi.project.system.noticeRecord.mapper.NoticeRecordMapper;
import com.ruoyi.project.system.user.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 公告 服务层实现
 *
 * @author ruoyi
 * @date 2018-06-25
 */
@Service
public class NoticeServiceImpl implements INoticeService {
  @Autowired
  private NoticeMapper noticeMapper;
  @Autowired
  private NoticeRecordMapper noticeRecordMapper;
  @Autowired
  private SessionService sessionService;
  @Autowired
  private SimpMessagingTemplate template;

  /**
   * 查询公告信息
   *
   * @param noticeId 公告ID
   * @return 公告信息
   */
  @Override
  public Notice selectNoticeById(Long noticeId) {
    return noticeMapper.selectNoticeById(noticeId);
  }

  /**
   * 查询公告列表
   *
   * @param notice 公告信息
   * @return 公告集合
   */
  @Override
  public List<Notice> selectNoticeList(Notice notice) {
    return noticeMapper.selectNoticeList(notice);
  }

  /**
   * 新增公告
   *
   * @param notice 公告信息
   * @return 结果
   */
  @Override
  public int insertNotice(Notice notice) {
    notice.setCreateBy(ShiroUtils.getLoginName());
    return noticeMapper.insertNotice(notice);
  }

  /**
   * 保存公告
   *
   * @param notice 公告信息
   * @return 结果
   */
  @Override
  public int saveSendNotice(Notice notice) {
    notice.setCreateBy(ShiroUtils.getLoginName()); 
    int r = noticeMapper.insertNotice(notice);
    sendNoticeToUsers(notice);
    return r;
  }

  /**
   * 修改公告
   *
   * @param notice 公告信息
   * @return 结果
   */
  @Override
  public int updateNotice(Notice notice) {
    notice.setUpdateBy(notice.getCreateBy());
    int r = noticeMapper.updateNotice(notice);
    sendNoticeToUsers(notice);
    return r;
  }

  /**
   * 删除公告对象
   *
   * @param ids 需要删除的数据ID
   * @return 结果
   */
  @Override
  public int deleteNoticeByIds(String ids) {
    noticeRecordMapper.deleteNoticeRecordByNoticeIds(Convert.toStrArray(ids));
    return noticeMapper.deleteNoticeByIds(Convert.toStrArray(ids));
  }

  public void sendNoticeToUsers(Notice notice) {
    NoticeRecord noticeRecord = new NoticeRecord();
    noticeRecord.setNoticeId(notice.getNoticeId());
    List<NoticeRecord> list = noticeRecordMapper.selectNoticeRecordList(noticeRecord);
    if(list.size() > 0) {
      System.out.println("-----------ZMY-----------值= 单据 ID 为" + notice.getNoticeId() + "的单据已经发送成功  无须再次发送当前类=NoticeServiceImpl.sendNoticeToUsers()");
      return;
    } else {
      notice.setIsSend("0");
      noticeMapper.updateNotice(notice);
      Long[] userIds = StringUtils.strArrToLongArr(notice.getUserIds());
      Long notifyId = Long.valueOf(notice.getNoticeId());
      List<NoticeRecord> records = new ArrayList<NoticeRecord>();
      for (Long userId : userIds) {
        NoticeRecord record = new NoticeRecord();
        record.setNoticeId(notifyId);
        record.setUserId(userId);
        record.setIsRead(0);
        records.add(record);
      }
      noticeRecordMapper.batchSave(records);
      //给在线用户发送通知
      ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1, 0, TimeUnit.MILLISECONDS, new LinkedBlockingDeque<>());
      executor.execute(new Runnable() {
        @Override
        public void run() {
          for (User userDO : sessionService.listOnlineUser()) {
            for (Long userId : userIds) {
              if(userId.equals(userDO.getUserId())) {
                System.out.println("-----------ZMY-----------值=" + userDO.getUserId() + "," + "当前类=NoticeServiceImpl.run()");
                template.convertAndSendToUser(userDO.toString(), "/queue/notifications", "新消息：" + notice.getNoticeTitle());
              }
            }
          }
        }
      });
      executor.shutdown();
    }
  }

}
